<template>
	<div class="addMold">
		<!-- 新增编辑 -->
		<Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout" width="80%">
			<div class="content-item">
				<Row>
					<Col class="pd16">
						<Form ref="form" :disabled="disabled" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
							<Row :gutter="20">
								<Col span="8">
									<FormItem label="工装BOM名称" prop="moldName">
										<Input type="text" maxlength="100" v-model="formItem.moldName" :placeholder="`${$t('common.inputInfo')}`" />
									</FormItem>
								</Col>
								<Col span="8">
									<FormItem label="工装BOM编号" prop="moldCode">
										<Input
											type="text"
											maxlength="100"
											:disabled="viewType == 'edit'"
											v-model="formItem.moldCode"
											:placeholder="`${$t('common.inputInfo')}`"
										/>
									</FormItem>
								</Col>
								<Col span="8">
									<FormItem label="是否启用" prop="state">
										<Select v-model="formItem.state" :placeholder="`${$t('common.selectInfo')}`">
											<Option :value="1" label="是"> </Option>
											<Option :value="0" label="否"> </Option>
										</Select>
									</FormItem>
								</Col>
							</Row>
							<Row :gutter="20">
								<Col span="8">
									<FormItem label="工装位置" prop="functionalLocation">
										<Cascader
											clearable
											:data="orgList"
											v-model="formItem.functionalLocation"
											:placeholder="`${$t('common.selectInfo')}`"
											change-on-select
										>
										</Cascader>
									</FormItem>
								</Col>
								<Col span="8">
									<FormItem label="工装BOM版本号" prop="bomVersion">
										<Input type="text" maxlength="10" v-model="formItem.bomVersion" :placeholder="`${$t('common.inputInfo')}`" />
									</FormItem>
								</Col>
								<Col span="8">
									<FormItem label="备注" prop="remarks">
										<Input type="text" maxlength="200" v-model="formItem.remarks" :placeholder="`${$t('common.inputInfo')}`" />
									</FormItem>
								</Col>
							</Row>
							<Row :gutter="20">
								<Table
									class="resizable-table"
									border
									@on-column-width-resize="onColumnWidthResize"
									:columns="columnsAdd"
									ellipsis
									ref="selection"
									stripe
									:data="dataArr"
									@on-selection-change="onSelectChange"
									@on-select="onSelect"
								>
									<template slot-scope="{ index }" slot="moldCode">
										<Select
											style="width: 100%"
											v-model="dataArr[index].equipCode"
											filterable
											clearable
											label-in-value 
											:transfer="true"
											:placeholder="`${$t('common.inputInfo')}`"
											@on-select="(value) => listChange(value,index,'equipCode')"
										>
											<Option v-for="(item, index) of planList" :tag="item.id" :value="item.equipCode" :key="index" :label="item.equipCode"> </Option>
										</Select>
									</template>
									<template slot-scope="{ row, index }" slot="moldName">
										<Select
											style="width: 100%"
											v-model="dataArr[index].equipName"
											filterable
											clearable
											:transfer="true"
											:placeholder="`${$t('common.inputInfo')}`"
											@on-select="(value) => listChange(value,index,'equipName')"
										>
											<Option v-for="(item, index) of planList" :tag="item.id" :value="item.equipName" :key="index" :label="item.equipName"> </Option>
										</Select>
									</template>
									<template slot-scope="{ index }" slot="action">
										<span class="operationBtn" style="cursor: pointer" @click="delPrrShowH(index)"
											><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span
										>
									</template>
								</Table>
								<Button class="mt16" type="default" @click="dataArrPush">+添加一行</Button>
							</Row>
						</Form>
					</Col>
				</Row>
			</div>
			<div slot="footer">
				<Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
				<Button type="primary" v-if="!disabled" :loading="loading" @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
				<Button type="primary" v-if="!disabled" :loading="loading" @click="addOk('form', 'publish')">确认并发布</Button>
			</div>
		</Modal>
	</div>
</template>
<script>
import toggleTableOperation from '@/mixins/toggleTableOperation';
import recursion from '@/util/recursion';

export default {
	name: 'addModal',
	mixins: [toggleTableOperation],
	data() {
		const validateNumber = (rule, val, callback, message) => {
			if (val !== '') {
				return callback();
			}
			return callback(new Error(message));
		};
		return {
			columnsAdd: [
				{
					key: 'selection',
					type: 'selection',
					width: 60,
					align: 'center',
				},
				{
					title: '序号',
					width: 80,
					align: 'center',
					render: (h, params) => {
						return h('span', params.index + 1);
					},
				},
				{
					title: '工装编号',
					key: 'moldCode',
					slot: 'moldCode',
					minWidth: 220,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装名称',
					key: 'moldName',
					slot: 'moldName',
					minWidth: 200,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装类型',
					key: 'moldModel',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装产品型号',
					key: 'moldState',
					minWidth: 160,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装状态',
					key: 'moldState',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '生产次数',
					key: 'productionMode',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '是否启用',
					key: 'isEnabled',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
					render: (h, params) => {
						return h('span', params.row.isEnabled == 1 ? '是' : '否');
					},
				},
				{
					title: '二级保养次数',
					key: 'messageMaintenanceMode',
					minWidth: 160,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '二级实际保养模次',
					key: 'maintenanceMode',
					minWidth: 160,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '三级保养模次',
					key: 'messageMaintenanceModeThree',
					minWidth: 160,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装等级',
					key: 'moldGrade',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '评分',
					key: 'score',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '日定额',
					key: 'dayQuota',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工时定额（PCS/H）',
					key: 'hourQuota',
					minWidth: 189,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '理论节拍(S)',
					key: 'moldingCycle',
					minWidth: 120,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装寿命',
					key: 'moldLife',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装剩余寿命',
					key: 'moldResidueLife',
					minWidth: 130,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '功能位置',
					key: 'functionalLocationName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '库区',
					key: 'reservoirArea',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '库位',
					key: 'warehouseLocation',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '利用率',
					key: 'useRate',
					minWidth: 140,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '创建人',
					key: 'maintainer',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '创建时间',
					key: 'maintenanceTime',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '操作',
					slot: 'action',
					fixed: 'right',
					minWidth: 100,
					align: 'center',
				},
			],
			planList: [],
			orgList: [],
			create: false,
			viewType: 'edit',
			disabled: false,
			formItem: {},
			addtitle: {},
			dataArr: [],
			ruleValidate: {
				moldName: [{ required: true, message: this.$t('common.inputInfo') }],
				moldCode: [{ required: true, message: this.$t('common.inputInfo') }],
				moldModel: [{ required: true, message: this.$t('common.inputInfo') }],
				cavityNum: [{ required: true, message: this.$t('common.inputInfo') }],
				messageMaintenanceMode: [{ required: true, message: this.$t('common.inputInfo') }],
				messageMaintenanceModeThree: [{ required: true, message: this.$t('common.inputInfo') }],
				bomVersion: [{ required: true, message: this.$t('common.inputInfo') }],
				moldingCycle: [{ required: true, validator: validateNumber, message: this.$t('common.inputInfo') }],
				score: [{ required: true, message: this.$t('common.inputInfo') }],
				moldState: [{ required: true, message: this.$t('common.selectInfo') }],
			},
		};
	},
	mounted() {
		this.getOrgList();
		this.getCenterList();
	},
	methods: {
		getOrgList() {
			this.axios({
				method: 'get',
				url: '/basic/organization/findListByToken',
				params: { level: 0 },
			}).then((res) => {
				if (res.code === 200) {
					const obj = {
						label: 'name',
						value: 'code',
						children: 'children',
					};
					this.orgList = recursion.convertTree(res.data, obj);
				} else {
					this.$Message.warning({ content: res.msg, duration: 6, closable: true });
				}
			});
		},
		dataArrPush() {
			const len = this.dataArr.length;
			if (len == 0 || this.dataArr[len - 1].equipCode) {
				this.dataArr.push({});
			} else {
				this.$Message.warning({
					content: '请将数据填写完整后再添加',
					duration: 6,
					closable: true,
				});
			}
		},
		getCenterList() {
			// if (this.create == false) {
			// 	return;
			// }
			this.axios({
				method: 'post',
				url: '/dms/equipInfo/selectList',
				// url: '/dms/equipInfo/queryEquipfoList',
				data: { pageSize: 10, pageNum: 1 },
			}).then((res) => {
				if (res.code === 200) {
					this.planList = res.data || [];
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		listChange(value,index,key) {
			const checkOnlyOne =  ()=> {
				// if (this.dataArr.length == 0) {
				// 	return -1;
				// } else {
					const repeatIndex = this.dataArr.findIndex((data) => data.id == value.tag);
					return repeatIndex;
				// }
			};

			if (value.tag == undefined) {
				this.$set(this.dataArr, index, {});
			} else {
				const repeatIndex = checkOnlyOne();
				if (repeatIndex !== -1) {
					this.$Message.warning({ content: `该数据与第${repeatIndex + 1}条重复，请勿重复添加！`, duration: 6, closable: true });
					setTimeout(() => {
						this.$set(this.dataArr, index, {});
					}, 300);
					return false;
				}
				this.$set(this.dataArr, index, this.planList.find((data) => data.id == value.tag));
			}
		},
		delPrrShowH(index) {
			this.dataArr.splice(index, 1);
		},
		//增加或编辑
		createfaultCodeShowH(row) {
			this.disabled = false;
			this.$refs.form.resetFields();
			if (row.id) {
				this.viewType = 'edit';
				this.addtitle = `${this.$t('common.Edit')}`;
				this.axios({
					url: '/dms/moldInfo/getDetailById',
					method: 'get',
					params: { moldId: row.id },
				}).then((res) => {
					this.formItem = res.data || {};
					this.$set(this, 'dataArr', res.data.equipInfoList || []);
					delete this.formItem.equipInfoList;
					this.create = true;
				});
			} else {
				this.viewType = 'add';
				this.addtitle = `${this.$t('common.New')}`;
				this.formItem = {
					state: 0,
				};
				this.dataArr = [];
				this.create = true;
			}
		},
		addOk(name, type) {
			if (type == 'publish' && this.dataArr && this.dataArr.length == 0) {
				this.$Message.warning({
					content: '请维护工装信息！',
					duration: 6,
					closable: true,
				});
				return;
			}
			const equipIdList = this.dataArr.map((f) => f.id);
			const result = equipIdList.filter((item) => item !== null && item !== undefined && item !== '');
			if (equipIdList.length !== result.length) {
				this.$Message.warning({
					content: '请将信息填写完整！',
					duration: 6,
					closable: true,
				});
				console.log(equipIdList.length, result.length);
				return;
			}
			this.$refs[name].validate((valid) => {
				if (!valid) {
					return;
				} else {
					this.loading = true;
					if (this.formItem.id) {
						this.axios({
							method: 'put',
							url: '/dms/moldInfo/update',
							data: {
								...this.formItem,
								isPublish: type == 'publish' ? 1 : 0,
								equipIdList,
							},
						}).then((res) => {
							this.loading = false;
							if (res.code === 200) {
								this.$emit('changeNum');
								this.$Message.success('修改成功');
								this.create = false;
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					} else {
						this.axios({
							method: 'post',
							url: '/dms/moldInfo/save',
							data: {
								...this.formItem,
								equipIdList,
								isPublish: type == 'publish' ? 1 : 0,
							},
						}).then((res) => {
							this.loading = false;
							if (res.code === 200) {
								this.$emit('changeNum');
								this.$Message.success('新增成功');
								this.create = false;
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					}
				}
			});
		},
		keyUp(e, key, money) {
			// 如果是删除为空 则不处理
			if (!this.formItem[key]) {
				return (this.formItem[key] = '');
			}
			// 每次抬键处理,对应金额渲染两位小数||数字
			let num = '';
			if (money) {
				num = this.formItem[key].match(/^\d*(\.?\d{0,2})/g)[0];
			} else {
				num = this.formItem[key].replace(/^[^\d]+$/g, '').split('.')[0];
			}
			this.formItem[key] = `${num}`;
		},
		keyUp5(e, key, money) {
			if (!this.formItem[key]) {
				return (this.formItem[key] = '');
			}
			let num = '';
			if (money) {
				num = this.formItem[key].match(/^\d*(\.?\d{0,5})/g)[0];
			} else {
				num = this.formItem[key].replace(/^[^\d]+$/g, '').split('.')[0];
			}
			this.formItem[key] = `${num}`;
		},
	},
};
</script>

<style scoped lang="scss">
::v-deep .ivu-table-cell-slot {
	.ivu-form-item {
		// margin-bottom: 16px !important;
	}
}
</style>
